import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:management/const/consts.dart';
import 'package:management/const/flags.dart';
import 'package:management/const/init.dart';
import 'package:management/const/theme.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/user/LoginResponse.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/toast.dart';
import 'package:management/main.dart';

import 'state.dart';

class SignInScreenLogic extends GetxController {
  final SignInScreenState state = SignInScreenState();

  @override
  void onReady() {
    _getSavedInformation();
  }

  void getEmailOrPhone(String value) {
    if (value.isNum && value.length == 11) {
      state.phoneNumber.value = value;
      // print(value + 'is phone');
      state.hasError.value = false;
    } else if (value.isEmail) {
      state.email.value = value;
      // print(value + 'is email');
      state.hasError.value = false;
    } else if (value.isNotEmpty) {
      state.hasError.value = true;
    } else {
      state.hasError.value = false;
    }

    _checkSubmitState();

    update();
  }

  void getPassword(String value) {
    // print(value);
    state.password.value = value;

    _checkSubmitState();
  }

  void rememberMe(bool? value) {
    state.checkBox.value = !state.checkBox.value;
  }

  void submit() {
    if (state.phoneNumber.isNotEmpty && state.password.isNotEmpty) {
      LoadingElement.loadingDialog(() async {
        return false;
      });
      MyHttpClient.signIn(state.phoneNumber.value, state.password.value)
          .then((value) => _saveLoginInformation(value));
    }

    if (state.email.isNotEmpty && state.password.isNotEmpty) {
      LoadingElement.loadingDialog(() async {
        return false;
      });
      MyHttpClient.signIn(state.email.value, state.password.value)
          .then((value) => _saveLoginInformation(value));
    }
    return;
  }

  void signInWithQQ() {
    Get.snackbar("敬请期待", "暂不支持此QQ功能",
        backgroundGradient: LinearGradient(
            colors: [MyColor.gradientBlue[0]!, MyColor.gradientBlue[1]!]));
    Get.changeTheme(AppTheme.lightTheme);
  }

  void signInWithWechat() {
    Get.snackbar("敬请期待", "暂不支持此WeChat功能",
        colorText: MyColor.white,
        backgroundGradient: LinearGradient(
            colors: [MyColor.gradientGreen[0]!, MyColor.gradientGreen[1]!]));
    Get.changeTheme(AppTheme.darkTheme);
  }

  void signInWithOthers() {}

  void forgetPassword() {
    // Get.snackbar("忘记", state.phoneNumber + state.password);
    Get.toNamed(RouteConfig.forgetPasswordScreen);
  }

  void toSignUp() {
    Get.offNamed(RouteConfig.signUpScreen);
  }

  void _checkSubmitState() {
    if (state.password.isNotEmpty && state.phoneNumber.isNotEmpty) {
      state.canSubmit.value = true;
    } else if (state.password.isNotEmpty && state.email.isNotEmpty) {
      state.canSubmit.value = true;
    } else {
      state.canSubmit.value = false;
    }
  }

  Future<void> _saveLoginInformation(LoginResponse value) async {
    if (value.code == 200) {
      GlobalInit.saveSpData(SPFlag.accessToken, value.data!.accessToken!);
      GlobalInit.saveSpData(SPFlag.refreshToken, value.data!.refreshToken!);
      GlobalInit.saveSpData(SPFlag.expiresIn, value.data!.expiresIn!);
      GlobalInit.saveSpData(SPFlag.idToken, value.data!.idToken!);
      GlobalInit.saveSpData(SPFlag.tokenType, value.data!.tokenType!);
      if (state.checkBox.isTrue) {
        GlobalInit.saveSpData(SPFlag.accountPhone, state.phoneNumber.value);
        GlobalInit.saveSpData(SPFlag.accountEmail, state.email.value);
        GlobalInit.saveSpData(SPFlag.password, state.password.value);
      } else {
        GlobalInit.removeSpData(SPFlag.accountPhone);
        GlobalInit.removeSpData(SPFlag.accountEmail);
        GlobalInit.removeSpData(SPFlag.password);
      }
      // 判断是否进入编辑信息界面
      MyHttpClient.getUserData().then((value) {
        // 第一次登录不会生成真名-据此判断跳转
        if (value.data!.realName != null) {
          Get.back();
          Get.offAllNamed(RouteConfig.homeScreen);
        } else {
          Get.back();
          Get.offNamed(RouteConfig.editProfileScreen);
        }
      });
    } else {
      Get.back();
      Utils.toastError(value.msg);
    }
  }

  Future<void> _getSavedInformation() async {
    final String? phone = GlobalInit.getSpData(SPFlag.accountPhone);
    final String? email = GlobalInit.getSpData(SPFlag.accountEmail);
    final String? pwd = GlobalInit.getSpData(SPFlag.password);
    if (phone != null) {
      state.controllerAccount.text = phone;
      state.phoneNumber.value = phone;
    }
    if (email != null) {
      state.controllerAccount.text = email;
      state.email.value = email;
    }
    if (pwd != null) {
      state.controllerPwd.text = pwd;
      state.password.value = pwd;
    }
  }
}
